package com.yc.demo.d0316;

import com.google.gson.Gson;
import com.yc.demo.util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "QueryServlet", value = "/QueryServlet.s")
public class QueryServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookname = request.getParameter("bookname");
        String bookauthor = request.getParameter("bookauthor");
        String pageSize = request.getParameter("pageSize");
        String currentPage = request.getParameter("currentPage");
        int size = Integer.valueOf(pageSize);
        int page = Integer.valueOf(currentPage);
        int begin = size*(page-1);
        //组合条件查询
        String sql = "select * from books where 1=1  ";
        List<Object> params = new ArrayList<>();
        if (bookname!=null &&bookname.trim().isEmpty()==false){
            sql += " and bookname like concat('%',?,'%') ";
            params.add(bookname);
        }
        if (bookauthor!=null &&bookauthor.trim().isEmpty()==false){
            sql += " and bookauthor like concat('%',?,'%') ";
            params.add(bookauthor);
        }
        long total = DBHelper.count(sql,params.toArray());
        params.add(begin);
        params.add(size);
        List<Map<String, Object>> data = DBHelper.selectListMap(sql + "limit ? , ?", params.toArray());
        //查询总行数

        Map<String,Object> result = new HashMap<>();
        result.put("data",data);
        result.put("total",total);
        String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
